<template>
  <div class="cusAdd">
    <van-nav-bar
        :title="isDetail ? '详情' :getTitle"
        left-arrow
        left-text="返回"
        @click-left="back"/>
    <div class="titleWrapper" v-show="isDetail">
      <div class="customerStyle">
        <van-tag color="pink">
          客户资料
        </van-tag>
      </div>
      <div class="titleItem">
        <div>{{ formObj.fname }}</div>
      </div>
      <div class="customerStyle">
        <van-tag color="orange">
          {{ formObj.ftypeName }}
        </van-tag>
      </div>
    </div>
    <div class="tagWrapper" v-show="isDetail">
      <div class="tagItem">
        <van-tag color="#ccc">
          负责人: {{ formObj.fuser}}
        </van-tag>
      </div>
      <div class="tagItem">
        <van-tag color="#ccc">
          共享人: {{ formObj.fshareName}}
        </van-tag>
      </div>
      <div class="tagItem">
        <van-tag color="#ccc">
          建立日期: {{ formObj.createTime}}
        </van-tag>
      </div>
    </div>
    <!--豆腐块-->
    <div class="tagContent" v-show="isDetail">
      <div class="tagContentItem" @click="toFollowRecord(formObj.id, 1)">
        <div class="tagContentTitle">
          <div class='tagNumber'>{{ formObj.sjNum }}</div>
<!--          <div class='tagUnit'>条</div>-->
        </div>
        <div class="tagContentName">
          商机
        </div>
      </div>
      <div class="tagContentItem" @click="toFollowRecord(formObj.id, 2)">
        <div class="tagContentTitle">
          <div class='tagNumber'>{{ formObj.rcNum }}</div>
<!--          <div class='tagUnit'>元</div>-->
        </div>
        <div class="tagContentName">
          日程
        </div>
      </div>
    </div>
    <div class="wrapper">
      <van-form label-width="120" validate-first @failed="onFailed" @submit="onSubmit" style="width: 95%;" :disabled="isDetail">
        <div class="InfoCard">
          <van-field
              disabled
              name="fnumber"
              v-model="formObj.fnumber"
              label="代码"
          />
          <van-field
              :readonly="!isReqired"
              :disabled="isDetail"
              name="fname"
              v-model="formObj.fname"
              label="名称"
              required
              :rules="[{ required: true, trigger: 'onSubmit', message: '请输入名称' }]"
          >
            <template #button>
              <van-button v-show="!isDetail" size="small" native-type="button" type="info" icon="search" @click="choosedFnameInfo">查找</van-button>
            </template>
          </van-field>
          <van-field
              :disabled="isDetail"
              name="fcreditcode"
              v-model="formObj.fcreditcode"
              label="统一社会信用代码"
              :required="isReqired"
              :rules="[{ required: isReqired, trigger: 'onSubmit', message: '请输入统一社会信用代码' }]"
          />
          <van-field
              :disabled="isDetail"
              name="flegalperson"
              v-model="formObj.flegalperson"
              label="法定代表人"
              :required="isReqired"
              :rules="[{ required: isReqired, trigger: 'onSubmit', message: '请输入法定代表人' }]"
          />
          <van-field
              :disabled="isDetail"
              readonly
              clickable
              name="fbusinessStatus"
              v-model="formObj.fbusinessStatus"
              label="经营状态"
              :required="isReqired"
              @click="chooseFun('经营状态', columnsFbusinessStatus,1)"
              :rules="[{ required: isReqired, trigger: 'onSubmit', message: '请选择经营状态' }]"
          />
          <van-field
              :disabled="isDetail"
              name="fstartDate"
              v-model="formObj.fstartDate"
              label="成立日期"
              readonly
              clickable
              @click="chooseExpDate()"
              :required="isReqired"
              :rules="[{ required: isReqired, trigger: 'onSubmit', message: '请选择成立日期' }]"
          />
          <van-field
              :disabled="isDetail"
              type="number"
              name="fregistCapi"
              v-model="formObj.fregistCapi"
              label="注册资本"
              :required="isReqired"
              :rules="[{ required: isReqired, trigger: 'onSubmit', message: '请输入注册资本' }]"
          />
          <van-field
              :disabled="isDetail"
              name="fqualificationName"
              v-model="formObj.fqualificationName"
              label="纳税人资质"
              readonly
              clickable
              :required="isReqired"
              @click="chooseFun('纳税人资质', columnsFqualification,2)"
              :rules="[{ required: isReqired, trigger: 'onSubmit', message: '请选择纳税人资质' }]"
          />
          <van-field
              :disabled="isDetail"
              name="faddress"
              v-model="formObj.faddress"
              label="注册地址"
              :required="isReqired"
              :rules="[{ required: isReqired, trigger: 'onSubmit', message: '请输入注册地址' }]"
          />
          <van-field
              :disabled="isDetail"
              name="findustryName"
              v-model="formObj.findustryName"
              label="行业"
              readonly
              clickable
              :required="isReqired"
              @click="chooseFun('行业', columnsFindustry,3)"
              :rules="[{ required: isReqired, trigger: 'onSubmit', message: '请选择行业' }]"
          />
          <van-field
              :disabled="isDetail"
              name="fcustomerNatureName"
              v-model="formObj.fcustomerNatureName"
              label="客户性质"
              readonly
              clickable
              @click="chooseFun('客户性质', columnsFnature1,4)"
          />
          <van-field
              :disabled="isDetail"
              name="fcompanyNatureName"
              v-model="formObj.fcompanyNatureName"
              label="公司性质"
              readonly
              clickable
              @click="chooseFun('公司性质', columnsFnature2,5)"
          />
          <van-field
              :disabled="isDetail"
              name="fregionName"
              v-model="formObj.fregionName"
              label="区域分类"
              readonly
              clickable
              @click="chooseFun('区域分类', columnsFregion,6)"
          />
          <van-field
              :disabled="isDetail"
              name="fsourceName"
              v-model="formObj.fsourceName"
              label="客户来源"
              readonly
              clickable
              @click="chooseFun('客户来源', columnsKhsource,7)"
          />
          <van-field
              :disabled="isDetail"
              name="fdeptidName"
              v-model="formObj.fdeptidName"
              label="部门"
              readonly
              clickable
              @click="chooseFun('部门', columnsFdeptid,8)"
          />
        </div>
        <!--联系人-->
        <div class="InfoCard" v-show="isDetail">
          <div class="ClumnBar">
            <van-tag mark type="primary" size="large">联系人信息</van-tag>
          </div>
          <div v-for="(contract, idx) in contractList" :key="idx">
            <div class="ClumnBar">
              <van-tag mark type="primary" round color="#1989fa">{{ idx + 1 }}</van-tag>
            </div>
            <van-swipe-cell>
              <van-field
                  :disabled="isDetail"
                  v-model="contract.fusername"
                  label="姓名"
                  placeholder="请输入姓名"
              />
              <van-field
                  :disabled="isDetail"
                  v-model="contract.fphone"
                  label="手机"
                  placeholder="请输入手机"
              />
              <van-field
                  :disabled="isDetail"
                  v-model="contract.fwechat"
                  label="微信"
                  placeholder="请输入微信"
              />
              <van-field
                  :disabled="isDetail"
                  v-model="contract.femail"
                  label="邮件"
                  placeholder="请输入邮件"
              />
              <van-field
                  :disabled="isDetail"
                  v-model="contract.faddress"
                  label="地址"
                  placeholder="请输入地址"
              />
              <van-field
                  :disabled="isDetail"
                  v-model="contract.fposition"
                  label="职务"
                  placeholder="请输入职务"
              />
              <van-field
                  :disabled="isDetail"
                  v-model="contract.fnote"
                  rows="2"
                  autosize
                  label="备注"
                  type="textarea"
                  placeholder="请输入备注"
              />
              <van-field
                  :disabled="isDetail"
                  v-model="contract.froleName"
                  label="角色"
                  placeholder="请选择角色"
              />
              <van-field
                  :disabled="isDetail"
                  v-model="contract.fstandpointName"
                  label="立场"
                  placeholder="请选择立场"
              />
              <van-field
                  :disabled="isDetail"
                  v-model="contract.fcontactStateName"
                  label="接触状态"
                  placeholder="请选择接触状态"
              />
              <van-field
                  :disabled="isDetail"
                  v-model="contract.frelationshipName"
                  label="客情关系"
                  placeholder="请选择客情关系"
              />
              <!--            <template #right>-->
              <!--              <van-button :disabled="isFollow || isDetail" square text="删除" type="danger" class="delete-button" @click="handleDeleteContract(idx)"/>-->
              <!--            </template>-->
            </van-swipe-cell>
          </div>
        </div>
        <div style="margin: 16px;" v-show="!isDetail">
          <van-button :loading="loading" block type="info" native-type="submit">{{ ifNewAdd ? '提交' : '保存'}}</van-button>
        </div>
      </van-form>


      <!-- 选择弹框 -->
      <van-popup v-model="showPickerDate" position="bottom">
        <van-datetime-picker
            v-model="currentDate"
            type="date"
            title="成立日期"
            @confirm = "changeDate"
            @cancel="showPickerDate = false"
        />
      </van-popup>
      <!--数据字典选择-->
      <van-popup v-model="showPickerFun" position="bottom">
        <van-picker
            :title="choosetitle"
            show-toolbar
            :columns="columnsFun"
            @confirm="changeFun"
            @cancel="showPickerFun = false"
        />
      </van-popup>
    </div>
    <choose-fname-modal ref="chooseFnameModal" @ok="backFnameInfo"></choose-fname-modal>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { formatToString, filterObj } from '@/utils/utils'
import { queryByIdCustomer, editCustomer, addCustomer,getDicts, serCustomerContact } from '@/api/api'
import { Notify } from 'vant'
import ChooseFnameModal from "./chooseFnameModal";

export default {
  name: 'customerAdd',
  components: {
    ChooseFnameModal
  },
  data () {
    return {
      ftype: '',//记录下拉数据类型
      choosetitle: '',
      loading: false,
      ifNewAdd: true, // 新增还是编辑
      id: null, // 若是编辑记录id
      showPickerDate: false,
      showPickerFun: false,
      isReqired: false,
      formObj: {
        fnumber: '',
        fname: '',
        fcreditcode: '',
        flegalperson: '',
        fbusinessStatus: '',
        fstartDate: '',
        fregistCapi: '',
        fqualification: '',
        fqualificationName: '',
        faddress: '',
        findustry: '',
        findustryName: '',
        fcustomerNature: '',
        fcustomerNatureName: '',
        fcompanyNature: '',
        fcompanyNatureName: '',
        fregion: '',
        fregionName: '',
        fsource: '',
        fsourceName: '',
        fdeptid: '',
        fdeptidName: '',
      },
      currentDate: new Date(),
      columnsFun: [],
      columnsFbusinessStatus: [],
      columnsFqualification: [],
      columnsFindustry: [],
      columnsFnature1: [],
      columnsFnature2: [],
      columnsFregion: [],
      columnsKhsource: [],
      columnsFdeptid: [],
      contractList: [],
    }
  },
  computed: {
    ...mapState({
      openId: state => state.user.openId,
      realname: state => state.user.realname,
      access_token: state => state.app.access_token,
      ticket: state => state.app.ticket,
      appId: state => state.user.appId,
      fdeptid: state => state.user.fdeptid,
      fdeptidName: state => state.user.fdeptidName
    }),
    isDetail: function () {
      return this.$route.params.isDetail ? true : false
    },
    getTitle: function () {
      return this.ifNewAdd ? '新增' : '编辑'
    }
  },
  watch:{
    'formObj.fdeptid': {
      deep: true,
      immediate: true,
      handler (val) {
        if (val) {
          this.isReqired = val == 1 || val == 2 ? true : false
        }
      }
    }
  },
  created () {
    this.ifNewAdd =  this.$route.params.isAdd
    this.id = this.$route.params.id || ''
    if(!this.ifNewAdd) {
      this.getInfo()
    }else {
      this.formObj.fdeptidName = this.fdeptidName
      this.formObj.fdeptid = this.fdeptid
    }
    getDicts('fbusinessStatus').then(res => {
      if(res.success) {
        this.columnsFbusinessStatus= res.result.map(item => {
          return {
            text: item.text,
            code: item.value
          }
        })
      }
    })
    getDicts('fqualification').then(res => {
      if(res.success) {
        this.columnsFqualification= res.result.map(item => {
          return {
            text: item.text,
            code: item.value
          }
        })
      }
    })
    getDicts('findustry').then(res => {
      if(res.success) {
        this.columnsFindustry= res.result.map(item => {
          return {
            text: item.text,
            code: item.value
          }
        })
      }
    })
    getDicts('fnature1').then(res => {
      if(res.success) {
        this.columnsFnature1= res.result.map(item => {
          return {
            text: item.text,
            code: item.value
          }
        })
      }
    })
    getDicts('fnature2').then(res => {
      if(res.success) {
        this.columnsFnature2= res.result.map(item => {
          return {
            text: item.text,
            code: item.value
          }
        })
      }
    })
    getDicts('fregion').then(res => {
      if(res.success) {
        this.columnsFregion= res.result.map(item => {
          return {
            text: item.text,
            code: item.value
          }
        })
      }
    })
    getDicts('khsource').then(res => {
      if(res.success) {
        this.columnsKhsource= res.result.map(item => {
          return {
            text: item.text,
            code: item.value
          }
        })
      }
    })
    getDicts('fdeptid').then(res => {
      if(res.success) {
        this.columnsFdeptid= res.result.map(item => {
          return {
            text: item.text,
            code: item.value
          }
        })
      }
    })
  },
  methods: {
    getInfo () {
      queryByIdCustomer({ id: this.id }).then(res => {
        if (res.success) {
          let obj = res.result
          this.formObj = Object.assign({}, obj)
          this.isReqired = this.formObj.fdeptid == 1 || this.formObj.fdeptid == 2 ? true : false
        }
      })
      serCustomerContact({ id: this.id }).then(res => {
        if (res.success) {
          this.contractList = res.result
        }
      })
    },
    toFollowRecord (id, ftype) {
      this.$router.push({
        name: 'searchSjInfoList',
        params: {
          id,
          ftype
        }
      })
    },
    choosedFnameInfo () {
      this.$refs.chooseFnameModal.show()
    },
    backFnameInfo (info) {
      console.log(info)
      let data = info.result
      this.formObj.fname = data.Name
      this.formObj.fcreditcode = data.CreditCode
      this.formObj.flegalperson = data.OperName
      this.formObj.fbusinessStatus = data.Status
      this.formObj.fstartDate = data.StartDate
      this.formObj.faddress = data.Address
    },
    chooseExpDate () {
      this.showPickerDate = true
    },
    changeDate () {
      this.formObj.fstartDate = formatToString(this.currentDate, 'Simple', '-')
      this.showPickerDate = false
    },
    chooseFun (title, columns, ftype) {
      this.showPickerFun = true
      this.ftype = ftype
      this.choosetitle = title
      this.columnsFun = columns
    },
    changeFun (value) {
      switch (this.ftype) {
        case 1:
          this.formObj.fbusinessStatus = value.code
          break;
        case 2:
          this.formObj.fqualification = value.code
          this.formObj.fqualificationName = value.text
          break;
        case 3:
          this.formObj.findustry = value.code
          this.formObj.findustryName = value.text
          break;
        case 4:
          this.formObj.fcustomerNature = value.code
          this.formObj.fcustomerNatureName = value.text
          break;
        case 5:
          this.formObj.fcompanyNature = value.code
          this.formObj.fcompanyNatureName = value.text
          break;
        case 6:
          this.formObj.fregion = value.code
          this.formObj.fregionName = value.text
          break;
        case 7:
          this.formObj.fsource = value.code
          this.formObj.fsourceName = value.text
          break;
        case 8:
          this.formObj.fdeptid = value.code
          this.formObj.fdeptidName = value.text
          this.isReqired = value.code == 1 || value.code == 2 ? true : false
          break;
      }
      this.showPickerFun = false
    },
    onFailed () { // values, errors
      Notify({ type: 'warning', message: '请将信息填写完整!', duration: 4000 })
    },
    async onSubmit () {
      this.loading = true
      let params = {
        ...this.formObj
      }
      if (this.ifNewAdd) {
        addCustomer(params).then( res => {
          if (res.success) {
            Notify({ type: 'success', message: '我的客户新增成功!', duration: 4000 })
            this.back()
            this.loading = false
          }else {
            Notify({ type: 'danger', message: res.result, duration: 4000 })
            this.loading = false
          }
        })
      } else {
        delete params.createTime
        editCustomer(params).then(res => {
          if (res.success) {
            Notify({ type: 'success', message: '我的客户修改成功!', duration: 4000 })
            this.back()
            this.loading = false
          }
        })
      }

    },
    back () {
      this.$router.push({name: 'customerList'})
    }
  }
}
</script>
<style scoped>
.wrapper{
  background: #efefef;
  display: flex;
  justify-content: center;
}
.ContactOption{
  margin-bottom: 5px;
}
.ClumnBar{
  height: 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.delete-button {
  height: 100% !important;
}
.uploadWrapper {
  display: flex;
  flex-direction: column;
  color: #1989fa;
  font-size: 14px;
  margin-bottom: 2px;
}
.titleWrapper {
  /*width: 100%;*/
  margin: 8px;
  border-radius: 7px;
  display: flex;
  background-color: #ffffff;
  padding: 5px;
}
.titleItem {
  margin-right: 7px;
  font-weight: bold;
}
.customerStyle {
  height: 27px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-self: center;
}
.tagWrapper {
  margin: 8px;
  border-radius: 7px;
  display: flex;
  background-color: #ffffff;
  padding: 5px;
}
.tagItem {
  margin: 2px;
}
.tagContent {
  display: flex;
  height: 100px;
  border: 1px solid #ebeef5;
  box-shadow: 2px 2px #ebeef5;
  border-radius: 7px;
  background: #fff;
  margin: 7px;
}
.tagContentItem {
  width: 160px;
  height: 80px;
  margin: 10px  0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-right: 2px solid #ebeef5;
}
.tagContentTitle {
  display: flex;
  width: 100%;
  justify-content: center;
  align-items: baseline;
  padding-right: 2px;
}
.tagNumber {
  color: #ff0000;
  font-size: 18px;
  font-weight: bold;
  padding-right: 3px;
}
.tagUnit {
  color: #867d7b;
}
.tagContentName {
  font-size: 14px;
  color: #b4b4b4
}
</style>

